from datetime import datetime
from flask_login import UserMixin
from sqlalchemy import DateTime, Numeric
from werkzeug.security import generate_password_hash, check_password_hash
from applications.exts import db



# 购物车
class Carts(db.Model):
    __tablename__ = 'wx_carts'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='购物车id')
    openid = db.Column(db.String(60), db.ForeignKey('wx_user.openid'), comment='用户openid')
    gid = db.Column(db.Integer, db.ForeignKey('wx_goods.id'), comment='商品id')
    good_price = db.Column(db.Float, comment='商品价格')
    good_gname = db.Column(db.String(50), comment='商品名称')
    number = db.Column(db.Integer, comment='商品数量')
    good_photo = db.Column(db.String(99), comment='商品图片')
    update_time = db.Column(db.DateTime, default=datetime.now(), comment='更新时间')
    is_del = db.Column(db.Integer, default=0, comment='逻辑删除')



    def __str__(self):
        return self.id



    def to_dict(self):
        res = {}
        for col in self.__table__.columns:
            if isinstance(col.type, DateTime):  # 判断类型是否为DateTime
                if not getattr(self, col.name):  # 判断实例中该字段是否有值
                    value = ""
                else:  # 进行格式转换
                    value = getattr(self, col.name).strftime("%Y-%m-%d %H:%M:%S")
            elif isinstance(col.type, Numeric):  # 判断类型是否为Numeric
                value = float(getattr(self, col.name))  # 进行格式转换
            else:  # 剩余的直接取值
                value = getattr(self, col.name)
            res[col.name] = value
        return res
